package org.groupg.practice.configuration.validator;

import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.ConfigurationBuilderEvent;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;

public class EventDrivenValidator {
    public static void main(String[] args) {

        Parameters params = new Parameters();
        FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
                new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
                        .configure(params.properties().setFileName("app.properties"));

        // 添加事件监听器
        builder.addEventListener(ConfigurationBuilderEvent.CONFIGURATION_REQUEST, event -> {
            try {
                Configuration config = (Configuration) event.getSource().getConfiguration();
                new FilePathValidator("data.file").validate(config);
                new FilePathValidator("log.dir").validate(config);
            } catch (ConfigurationException e) {
                throw new RuntimeException("配置校验失败", e);
            }
        });

        try {
            PropertiesConfiguration config = builder.getConfiguration();
            System.out.println("配置加载成功！");
        } catch (ConfigurationException e) {
            System.err.println("错误: " + e.getMessage());
        }
    }
}